<script setup lang='ts'>
import { ref, reactive,onMounted } from 'vue'
import AccountTable from './ui/AccountTable.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RolesTable from './ui/RolesTable.vue'
import {
  GetAllUser,
  deleteUser,
  GetAllRoles,
  createUser,
  editUserInfo,
  resetUserPassword,
  addRoles,
  deleteRoles,
  editRoles,
  getAllPermission
} from '@/api/user'
import { 
  GetHarbor, 
  GetCompany 
} from '@/api/http'

// refs
const accountTableRef = ref()
const rolesTableRef = ref()

// 弹框
const accountVisible = ref(false)
const rolesVisible = ref(false)

// 弹框表单
const userFormData = reactive({
  userName: '',
  surname: '',
  roleId: '',
  harborCode: '',
  password: '',
  companyCode: '',
  emailAddress: ''
})
// 角色弹框
const roleFormData = reactive({
  roleName: '',
  description: '',
  isWarn: false,
  resourcePermissions: '',
  resourcePanels: '',
  resourcePanelItems: ''
})

// 是否为编辑
const isUpdate = ref(false)

// 角色列表
const roleList: any = ref([])
// 港口列表
let portList: any = ref([])
// 公司列表
let companyList: any = ref([])

// 表单验证
const validPassword = (userRules, value, callback) => {
  // ：字母大小写  数字  下划线 横线 正反斜线
  let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_ /\\//\-/\\]+$/
  if (!reg.test(value)) {
    callback(new Error('编号格式不正确，含有特殊字符!'))
  }
}

// 表单验证
const userRules = reactive({
  userName: [ { required: true, message: '不能为空', trigger: 'change' } ],
  surname: [ { required: true, message: '不能为空', trigger: 'change' } ],
  password: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { validator: validPassword, trigger: 'blur' }
  ],
  roleId: [ { required: true, message: '不能为空', trigger: 'change' } ],
  emailAddress: [
    { required: true, message: '请输入邮箱地址', trigger: 'change' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: [ 'blur', 'change' ]
    }
  ]
})
// 角色验证
const rolesRules = reactive({
  roleName: [ { required: true, message: '不能为空', trigger: 'change' } ]
})

// 定义函数
onMounted(() => {
  getRoleData()
  getPortList()
})
// 展示用户弹框
const showUserDialog = (num:number, row?: any) => {
  if(num) {
    console.log('编辑用户--------->')
    userFormData.userName = row.userName
    userFormData.surname = row.surname
    userFormData.roleId = row.roleId
    userFormData.harborCode = row.harborCode
    userFormData.password = row.password
    userFormData.companyCode = row.companyCode
    userFormData.emailAddress = row.emailAddress
    isUpdate.value = true
  } else {
    console.log('新增账号--------->')
    isUpdate.value = false
  }
  accountVisible.value = true
}
// 展示角色弹框
const showRolesDialog = (num: number, row?: any) => {
  if (num) {
    console.log('编辑角色--------->')
    roleFormData.description = row.description
    roleFormData.roleName = row.roleName
    roleFormData.isWarn = row.isWarn
    isUpdate.value = true
  } else {
    console.log('新增角色--------->')
    isUpdate.value = false
  }
  rolesVisible.value = true
}

// 获取角色列表
const getRoleData = () => {
  // 获取角色
  GetAllRoles({
    MaxResultCount: 999
  }).then(({ result }) => {
    roleList.value = result.items
    console.log('角色列表------>', roleList.value)
  })
}

// 获取港口列表
const getPortList = () => {
  portList.value = []
  GetHarbor({
    SkipCount: 0,
    MaxResultCount: 9999,
    Sorting: 'lastModificationTime desc'
  }).then(res => {
    portList.value = [ ...res.result.items ]
  })
}
// 获取公司列表
const getCompanyList = (e:any) => {
  companyList.value = []
  GetCompany({
    HarborCode: e
  }).then(res => {
    companyList.value = [ ...res.result.items ]
  })
}

// 确定
const determine = () => {
  if(accountVisible.value) {
    console.log('用户确认------->')
    if(isUpdate.value) {
      addUser()
    } else {
      updateUser()
    }
  }else {
    console.log('角色确认------->')
    if (isUpdate.value) {
      addRole()
    } else {
      updateRole()
    }
  }
}
// 添加用户
const addUser = () => {
  let form = {
    ...userFormData,
    roles: [ { id: userFormData.roleId } ],
    isActive: true,
    name: userFormData.surname
  }
  createUser({ ...form }).then(() => {
    ElMessage({
      type: 'success',
      message: '添加成功!'
    })
    accountTableRef.value.getUserList()
    accountVisible.value = false
  })
}
// 修改用户
const updateUser = () => {
  editUserInfo({ ...userFormData }).then(() => {
    ElMessage({
      type: 'success',
      message: '修改成功!'
    })
    accountTableRef.value.getUserList()
    accountVisible.value = false
  })
}

// 添加角色
const addRole = () => {
  addRoles({ ...roleFormData }).then(() => {
    rolesTableRef.value.getUserList()
    rolesVisible.value = false
  })
  createUser({ ...roleFormData }).then(() => {
    ElMessage({
      type: 'success',
      message: '添加成功!'
    })
    accountTableRef.value.getUserList()
    accountVisible.value = false
  })
}
// 修改角色
const updateRole = () => {
  editRoles({
    ...roleFormData,
    permissions: [
      ...roleFormData.resourcePermissions,
      ...roleFormData.resourcePanels,
      ...roleFormData.resourcePanelItems
    ]
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '修改成功!'
    })
    rolesTableRef.value.getUserList()
    rolesVisible.value = false
  })
}

// 取消
const cancellation = () => {
  console.log('查询------->')
  accountVisible.value = false
  rolesVisible.value = false
}

// 关闭弹框
const closeDialog = () => {
  userFormData.userName = ''
  userFormData.surname = ''
  userFormData.roleId = ''
  userFormData.harborCode = ''
  userFormData.password = ''
  userFormData.companyCode = ''
  userFormData.emailAddress = ''

  roleFormData.description = ''
  roleFormData.roleName = ''
  roleFormData.isWarn = false
}
</script>

<template>
  <div class="user-manage-main-box">
    <div class="account-box">
      <div class="title-box">
        <div>
          账号管理
        </div>
        <div
          class="add-account custom-button"
          @click="showUserDialog(0)"
        >
          添加账号
        </div>
      </div>
      <div class="table-box">
        <AccountTable
          ref="accountTableRef"
          :show-user-dialog="showUserDialog"
        />
      </div>
    </div>
    <div class="roles-box">
      <div class="title-box">
        <div>
          角色管理
        </div>
        <div
          class="add-roles custom-button"
          @click="showRolesDialog(0)"
        >
          添加角色
        </div>
      </div>
      <div class="table-box">
        <RolesTable
          ref="rolesTableRef"
          :show-roles-dialog="showRolesDialog"
        />
      </div>
    </div>
    <div class="dialog-box">
      <el-dialog
        v-model="accountVisible"
        width="960"
        :title="isUpdate ? '修改用户信息' : '增加用户'"
        @close="closeDialog"
      >
        <template #default>
          <div class="form-box">
            <el-form
              class="formStyle"
              :model="userFormData"
              :rules="userRules"
              label-width="130px"
            >
              <el-form-item
                label="用户名:"
                prop="userName"
              >
                <el-input v-model="userFormData.userName" />
              </el-form-item>

              <el-form-item
                label="姓名:"
                prop="surname"
              >
                <el-input
                  v-model="userFormData.surname"
                />
              </el-form-item>
              <el-form-item
                v-if="!isUpdate"
                label="密码:"
                prop="password"
              >
                <el-input
                  v-model="userFormData.password"
                  :disabled="isUpdate"
                />
              </el-form-item>
              <el-form-item
                label="角色"
                prop="roleId"
              >
                <el-select
                  v-model="userFormData.roleId"
                  class="stacker-reclaimer-select"
                >
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="港口"
              >
                <el-select
                  v-model="userFormData.harborCode"
                  class="stacker-reclaimer-select"
                  @change="getCompanyList"
                />
              </el-form-item>
              <el-form-item
                label="公司"
              >
                <el-select
                  v-model="userFormData.companyCode"
                  class="stacker-reclaimer-select"
                />
              </el-form-item>
              <el-form-item
                label="邮箱:"
                prop="emailAddress"
              >
                <el-input
                  v-model="userFormData.emailAddress"
                />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div class="form-btn-box">
            <el-button @click="cancellation">
              取 消
            </el-button>
            <el-button @click="determine">
              确 定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog
        v-model="rolesVisible"
        width="960"
        :title="isUpdate ? '修改角色信息' : '增加角色'"
        @close="closeDialog"
      >
        <template #default>
          <div class="form-box">
            <el-form
              class="formStyle"
              :model="roleFormData"
              :rules="rolesRules"
              label-width="130px"
            >
              <el-form-item
                label="姓名:"
                prop="roleName"
              >
                <el-input v-model="roleFormData.roleName" />
              </el-form-item>

              <el-form-item
                label="备注"
                prop="code"
              >
                <el-input
                  v-model="roleFormData.description"
                />
              </el-form-item>
              <el-form-item
                label="是否接受告警"
                label-width="120px"
              >
                <el-switch
                  v-model="roleFormData.isWarn"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancellation">
            取 消
          </el-button>
          <el-button @click="determine">
            确 定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped lang=scss>
.user-manage-main-box {
  width: 100%;
  height: 100%;

  >div {
    height: 49%;
    background-color: #fff;
  }

  .account-box {
    .title-box {
      display: flex;
      align-items: center;
      height: 60px;
      padding-left: 20px;
      border-bottom: 1px solid #dad7d7;

      .add-account {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 28px;
        margin-left: 15px;
        font-size: 14px;
      }
    }

    .table-box {
      margin-top: 15px;
      padding: 0 20px;
    }
  }

  .roles-box {
    margin-top: 20px;

    .title-box {
      display: flex;
      align-items: center;
      height: 60px;
      padding-left: 20px;
      border-bottom: 1px solid #dad7d7;

      .add-roles {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 28px;
        margin-left: 15px;
        font-size: 14px;
      }
    }

    .table-box {
      margin-top: 15px;
      padding: 0 20px;
    }
  }

  .form-btn-box {
    display: flex;
    justify-content: center;
    width: 100%;
  }

  .dialog-box {
    height: 0;
  }
}
</style>